package io.webfolder.cdp.channel;

import static java.nio.charset.StandardCharsets.UTF_8;

import com.neovisionaries.ws.client.ThreadType;
import com.neovisionaries.ws.client.WebSocket;
import com.neovisionaries.ws.client.WebSocketAdapter;
import com.neovisionaries.ws.client.WebSocketFrame;

import io.webfolder.cdp.session.MessageHandler;
import io.webfolder.cdp.session.SessionFactory;

public class NvWebSocketListener extends WebSocketAdapter {

	private final SessionFactory factory;

	private final MessageHandler handler;

	public NvWebSocketListener(SessionFactory factory, MessageHandler handler) {
		this.factory = factory;
		this.handler = handler;
	}

	@Override
	public void onTextMessage(WebSocket websocket, byte[] data) throws Exception {
		handler.process(new String(data, 0, data.length, UTF_8));
	}

	@Override
	public void onDisconnected(WebSocket websocket, WebSocketFrame serverCloseFrame, WebSocketFrame clientCloseFrame,
			boolean closedByServer) throws Exception {
		factory.close();
	}

	@Override
	public void onThreadCreated(WebSocket websocket, ThreadType threadType, Thread thread) throws Exception {
		thread.setName("cdp4j-WebSocket-" + thread.getName());
	}
}
